package com.ponhu.ea2.stockcenter.provider.utils;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.ponhu.ea2.stockcenter.vo.DingTalkContentVO;
import com.ponhu.ea2.wmscenter.model.utils.HttpClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static com.ponhu.ea2.stockcenter.enums.ResponseCodeEnum.*;

/**
 * @author luyu
 * @create 2021-11-06 17:54
 */
@Slf4j
@Component
public class DingTalkHandler {

    @Value("${ponhu.dingTalk.url}")
    private String url;

    @Value("${ponhu.GRAFANA_URL}")
    private String grafanaUrl;

    @Value("${spring.profiles.active}")
    private String active;

    /**
     * 发送钉钉机器人消息
     *
     * @param content    发送内容
     * @param mobileList 通知具体人的手机号码列表
     */
    public void sendMsg(String content, List<String> mobileList) {
        sendMsg(content, mobileList, false);
    }

    /**
     * 发送markDown格式数据（库存中心定制）
     * @param dingTalkContentVO
     */
    public void sendMsg(DingTalkContentVO dingTalkContentVO) {
        //OMS占用库存不足等，不发钉钉提醒
        if (ADD_OCCUPY_STOCK_EXCEPTION_900201.getCode().toString().equals(dingTalkContentVO.getExceptionCode()) ||
                DOC_NO_IS_EXISTS_EXCEPTION_900200.getCode().toString().equals(dingTalkContentVO.getExceptionCode()) ||
                STOCK_WAREHOUSE_EXCEPTION_900106.getCode().toString().equals(dingTalkContentVO.getExceptionCode()) ||
                PARAMS_INCORRECT_EXCEPTION_900003.getCode().toString().equals(dingTalkContentVO.getExceptionCode()) ||
                INVENTORY_EMPTY_EXCEPTION_900211.getCode().toString().equals(dingTalkContentVO.getExceptionCode())) {
            return;
        }
        dingTalkContentVO.setGrafanaUrl(grafanaUrl);
        sendMsg(dingTalkContentVO.getDingTalkMarkDownContent(), new ArrayList<>(), true);
    }

    /**
     * 发送markDown格式数据(通用)
     * @param dingTalkContentVO
     */
    public void sendMarkDownMsg(DingTalkContentVO dingTalkContentVO) {
        if(dingTalkContentVO == null){
            return;
        }
        dingTalkContentVO.setGrafanaUrl(grafanaUrl);
        sendMsg(dingTalkContentVO.toString(), null, true);
    }

    private void sendMsg(String content, List<String> mobileList, boolean isMarkDown) {
        try {
            //是否通知所有人
            boolean isAtAll = false;

            //如果具体人的手机号码列表为空则通知所有人
            if (CollectionUtils.isEmpty(mobileList)) {
                isAtAll = true;
                mobileList = Lists.newArrayList();
            }

            //组装请求内容
            String reqStr = buildReqStr(content, isAtAll, mobileList, isMarkDown);

            //推送消息（http请求）
            String result = HttpClient.getInstance().doPostJson(url, reqStr);
            log.info("发送钉钉机器人消息成功 ===>> Content={}", result);
        } catch (Exception e) {
            log.error("发送钉钉机器人消息异常 ===>> Error={}", e.getMessage());
        }
    }

    /**
     * 组装请求报文
     *
     * @param content
     * @param isAtAll    是否通知所有人
     * @param mobileList 通知指定的手机号，具体到某个人
     * @return
     */
    private static String buildReqStr(String content, boolean isAtAll, List<String> mobileList, boolean isMarkDown) {
        if(isMarkDown){
            //消息内容
            Map<String, String> contentMap = Maps.newHashMap();
            contentMap.put("title", "库存中心异常，快来人那～");
            contentMap.put("text", content);
            //通知人
            Map<String, Object> atMap = Maps.newHashMap();
            //是否通知所有人
            atMap.put("isAtAll", isAtAll);
            //通知具体人的手机号码列表
            atMap.put("atMobiles", mobileList);
            Map<String, Object> reqMap = Maps.newHashMap();
            reqMap.put("msgtype", "markdown");
            reqMap.put("markdown", contentMap);
            reqMap.put("at", atMap);
            return JSON.toJSONString(reqMap);
        }else {
            //消息内容
            Map<String, String> contentMap = Maps.newHashMap();
            contentMap.put("content", content);
            //通知人
            Map<String, Object> atMap = Maps.newHashMap();
            //是否通知所有人
            atMap.put("isAtAll", isAtAll);
            //通知具体人的手机号码列表
            atMap.put("atMobiles", mobileList);
            Map<String, Object> reqMap = Maps.newHashMap();
            reqMap.put("msgtype", "text");
            reqMap.put("text", contentMap);
            reqMap.put("at", atMap);
            return JSON.toJSONString(reqMap);
        }

    }

}
